package com.relife.sys.controller;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.relife.common.http.HttpUtil;
import com.relife.common.model.AjaxJson;
import com.relife.common.model.Client;
import com.relife.common.model.ClientManager;
import com.relife.common.model.Page;
import com.relife.common.utils.StringUtil;
import com.relife.core.easyui.Easyui;
import com.relife.core.entity.LogEntity;
import com.relife.core.entity.PermissionEntity;
import com.relife.core.entity.RoleEntity;
import com.relife.core.entity.UserEntity;
import com.relife.core.qbc.QbcQuery;
import com.relife.core.utils.ExcelUtil;
import com.relife.sys.service.AdminService;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;



@Controller
@RequestMapping("sys/user")
public class UserController extends BaseController {
	@Autowired
	private AdminService adminService;

	/**
	 * 页面
	 * 
	 * @author WU
	 * @date 2015-5-20 下午7:54:20
	 * @return
	 */
	@RequestMapping
	public String userList() {
		return "sys/user/userList";
	}

	/**
	 * 数据列表
	 * 
	 * @author WU
	 * @date 2015-5-20 下午7:54:08
	 * @param page
	 */
	@RequestMapping
	public void listData(UserEntity user, Page page, HttpServletResponse res) {
		QbcQuery qbc = new QbcQuery(user);
		qbc.add(Restrictions.isNotNull("password"));
		this.userPermission(qbc);
		service.getPage(qbc, page);
		Easyui.datagrid(page, res);
	}

	/**
	 * 
	 * @author WU
	 * @date 2015-6-20 上午2:11:30
	 * @param user
	 * @param req
	 * @return
	 */
	@RequestMapping
	public String user(UserEntity user, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(user.getId())) {
			user = adminService.get(UserEntity.class, user.getId());
		}
		req.setAttribute("page", user);
		return "sys/user/user";
	}

	/**
	 * 
	 * @author WU
	 * @date 2015-6-20 上午2:11:34
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson save(UserEntity user) {
		AjaxJson j = new AjaxJson();
		try {
			adminService.saveOrUpdateUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			j.setException(e);
		}
		return j;
	}

	/**
	 * 
	 * @author WU
	 * @date 2015-6-20 上午2:11:39
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/del")
	public AjaxJson del(UserEntity user) {
		AjaxJson j = new AjaxJson();
		try {
			adminService.delete(user);
		} catch (Exception e) {
			e.printStackTrace();
			j.setException(e);
		}
		return j;
	}

	/**
	 * 重置密码
	 * 
	 * @author WU
	 * @date 2016年12月21日 下午4:03:58
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson resetPwd(UserEntity user) {
		AjaxJson j = new AjaxJson();
		try {
			adminService.resetPwd(user);
		} catch (Exception e) {
			e.printStackTrace();
			j.setException(e);
		}
		return j;
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年4月26日 下午3:17:06
	 * @return
	 */
	@RequestMapping
	public String selectRole() {
		return "sys/user/selectRole";
	}

	/**
	 * 用户选择角色
	 * 
	 * @author WU
	 * @date 2016年6月13日 上午10:53:33
	 * @param role
	 * @param page
	 * @param res
	 * @param req
	 */
	@RequestMapping
	public void roleListData(RoleEntity role, Page page, HttpServletResponse res, HttpServletRequest req) {
		String departCodes = req.getParameter("departCodes");
		QbcQuery qbc = new QbcQuery(role, req.getParameterMap());
		if (StringUtil.isNotEmpty(departCodes)) {
			String[] dcode = departCodes.split(",");

			List<Criterion> critList = new ArrayList<Criterion>();
			for (int i = 0; i < dcode.length; i++) {
				if (dcode[i].indexOf("C") > 0 && dcode[i].indexOf("B") > 0) {
					String departC = dcode[i].substring(0, dcode[i].indexOf("C") + 3);
					critList.add(Restrictions.eq("depart.departCode", departC));

					String departB = dcode[i].substring(0, dcode[i].indexOf("B") > 0 ? dcode[i].indexOf("B") + 3 : 3);
					critList.add(Restrictions.eq("depart.departCode", departB));

				} else if (dcode[i].indexOf("B") > 0) {
					String departB = dcode[i].substring(0, dcode[i].indexOf("B") > 0 ? dcode[i].indexOf("B") + 3 : 3);
					critList.add(Restrictions.eq("depart.departCode", departB));
				}

			}

			if (critList.size() > 0) {
				qbc.add(Restrictions.or(critList.toArray(new Criterion[critList.size()])));
			}

			qbc.createAlias("depart", JoinType.INNER_JOIN);
		}
		this.openPermission(qbc);
		adminService.getPage(qbc, page);
		Easyui.datagrid(page, res);
	}

	/**
	 * 流程选择角色
	 * 
	 * @author WU
	 * @date 2016年12月23日 下午3:41:04
	 * @param role
	 * @param page
	 * @param res
	 * @param req
	 */
	@RequestMapping
	public void processRoleListData(RoleEntity role, Page page, HttpServletResponse res, HttpServletRequest req) {
		String departCodes = req.getParameter("departCodes");
		QbcQuery qbc = new QbcQuery(role, req.getParameterMap());
		if (StringUtil.isNotEmpty(departCodes)) {

			if (departCodes.indexOf("C") > 0 && departCodes.indexOf("B") > 0) {
				String departCode = departCodes.substring(0, departCodes.indexOf("C") + 3);
				departCodes = departCodes.substring(0, departCodes.indexOf("B") > 0 ? departCodes.indexOf("B") + 3 : 3);
				qbc.add(Restrictions.or(Restrictions.eq("depart.departCode", departCode), Restrictions.eq("depart.departCode", departCodes)));

			} else if (departCodes.indexOf("B") > 0) {
				departCodes = departCodes.substring(0, departCodes.indexOf("B") > 0 ? departCodes.indexOf("B") + 3 : 3);
				qbc.add(Restrictions.eq("depart.departCode", departCodes));
			}

			qbc.createAlias("depart", JoinType.INNER_JOIN);
		}
		this.openPermission(qbc);
		adminService.getPage(qbc, page);
		Easyui.datagrid(page, res);
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年4月26日 下午3:17:09
	 * @return
	 */
	@RequestMapping
	public String selectDepart() {
		return "sys/user/selectDepart";
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年4月26日 下午3:16:59
	 * @return
	 */
	@RequestMapping("/online")
	public String online() {
		return "sys/user/online";
	}

	/**
	 * 在线用户数据
	 * 
	 * @author WU
	 * @date 2015-5-20 下午7:54:08
	 * @param page
	 */
	@RequestMapping
	public void onlineData(UserEntity user, Page page, HttpServletResponse res) {
		LinkedHashMap<String, Client> map = ClientManager.getInstance().getClientMap();
		List<Client> list = new ArrayList<Client>();
		int m = 0;
		for (Client client : map.values()) {
			if (m >= ((page.getPage() - 1) * page.getRows()) && m < page.getPage() * page.getRows()) {
				list.add(client);
			}
			m++;
		}
		page.setList(list);
		page.setTotal(ClientManager.getInstance().getClientSize());
		Easyui.datagrid(page, res);
	}

	@RequestMapping("/logList")
	public String logList() {
		return "sys/user/logList";
	}

	/**
	 * 获取用户数据权限并组装
	 * 
	 * @author WU
	 * @date 2016年4月4日 下午2:38:11
	 * @return
	 */
	private void userPermission(QbcQuery qbc) {
		String url = HttpUtil.getRequest().getServletPath().substring(1);
		Client client = ClientManager.getInstance().getClientSession();
		String departCode = client.getDepart().getDepartCode();
		List<PermissionEntity> list = client.getPreList();
		Map<String, String> map = new HashMap<String, String>();

		if (list != null && list.size() > 0 && !client.getUser().isAdmin()) {
			for (int i = 0; i < list.size(); i++) {
				map.put(client.getUser().getId(), "userCode");
				departCode = MessageFormat.format(list.get(i).getDepartCode(), departCode);
				if (StringUtil.isNotEmpty(list.get(i).getUrl())) {
					if (list.get(i).getUrl().contains(url)) {
						map.put("%" + departCode + "%", "depCode");
					} else {
						continue;
					}
				} else {
					map.put("%" + departCode + "%", "depCode");
				}

			}
		}

		List<Criterion> clist = new ArrayList<Criterion>();
		for (String depCode : map.keySet()) {
			String value = map.get(depCode);
			if ("userCode".equals(value)) {
				clist.add(Restrictions.eq(value, depCode));
			} else {
				clist.add(Restrictions.like(value, depCode));
			}
		}
		if (map.size() > 0) {
			Criterion[] crits = new Criterion[map.size()];
			qbc.add(Restrictions.or(clist.toArray(crits)));
			qbc.add(Restrictions.like("depCode", "%"+client.getCompany().getDepartCode() + "%"));
		}
	}

	/**
	 * 数据列表
	 * 
	 * @author WU
	 * @date 2015-5-20 下午7:54:08
	 * @param page
	 */
	@RequestMapping
	public void logData(LogEntity log, Page page, HttpServletResponse res, HttpServletRequest req) {
		QbcQuery qbc = new QbcQuery(log, req.getParameterMap());
		this.openPermission(qbc);
		adminService.getPage(qbc, page);
		Easyui.datagrid(page, res);
		ExcelUtil.exportExcel(page, qbc, "用户操作日志列表");
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年6月13日 上午10:53:16
	 * @return
	 */
	@RequestMapping
	public String selectUser() {
		return "sys/user/selectUser";
	}

	/**
	 * @author WU
	 * @date 2016年6月13日 上午10:54:10
	 * @param user
	 * @param page
	 * @param res
	 */
	@RequestMapping
	public void selectUserData(UserEntity user, Page page, HttpServletResponse res) {
		user.setState(0);
		QbcQuery qbc = new QbcQuery(user);
		qbc.add(Restrictions.isNotNull("password"));
		adminService.getPage(qbc, page);
		Easyui.datagrid(page, res);
	}
}
